/********************************************************************************************
** Copyright � 2011 Nokia Corporation. All rights reserved.
** Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
** Java and all Java-based marks are trademarks or registered trademarks of
** Sun Microsystems, Inc. Other product and company names mentioned herein may be
** trademarks or trade names of their respective owners.
**
** Subject to the conditions below, you may, without charge:
**
** �  Use, copy, modify and/or merge copies of this software and
**    associated content and documentation files (the �Software�)
**
** �  Publish, distribute, sub-licence and/or sell new software
**    derived from or incorporating the Software.
**
** Some of the documentation, content and/or software maybe licensed under open source
** software or other licenses.  To the extent such documentation, content and/or
** software are included, licenses and/or other terms and conditions shall apply
** in addition and/or instead of this notice. The exact terms of the licenses, disclaimers,
** acknowledgements and notices are reproduced in the materials provided.
**
** This file, unmodified, shall be included with all copies or substantial portions
** of the Software that are distributed in source code form.
**
** The Software cannot constitute the primary value of any new software derived
** from or incorporating the Software.
**
** Any person dealing with the Software shall not misrepresent the source of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
********************************************************************************************/
import Qt 4.7


import "DCDataClasses.js" as DCDATA

Rectangle
{
    id: mytripsrect
    width: 300
    height: 110


    gradient: Gradient {
        GradientStop {
            position: 0.44
            color: "#abd1ee"
        }

        GradientStop {
            position: 1
            color: "#000000"
        }
    }

    z: 50

    property bool following: false


    property string datacloudurl: ""
    property string username: ""
    property string password: ""
    property string karpoid: ""

    property alias activerouteind: tripview.currentIndex

    signal showroute()

    signal drawImageOnMap(string id, double latitude, double longitude, string img, int xOffset, int yOffset)
    signal clearMap()

    signal startFollowing(string carpoolkarpoid)
    signal stopFollowing()


    ListModel
    {
        id: tripinfo
    }


    function getActiveInd()
    {
        return activerouteind
    }


    function getRouteOwnerName(ind)
    {
        if (ind < 0 || ind > tripview.count)
        {
            return "NA"
        }

        return tripinfo.get(ind).ownername
    }


    function getRouteOwnerHometown(ind)
    {
        if (ind < 0 || ind > tripview.count)
        {
            return "NA"
        }

        return tripinfo.get(ind).ownerhometown
    }

    function getRouteOwnerPhone(ind)
    {
        if (ind < 0 || ind > tripview.count)
        {
            return "NA"
        }

        return tripinfo.get(ind).ownerphone
    }

    function getRouteOwnerAlias(ind)
    {
        if (ind < 0 || ind > tripview.count)
        {
            return "NA"
        }

        return tripinfo.get(ind).owneralias
    }


    function getRouteTimeInd(ind)
    {
        if (ind < 0 || ind > tripview.count)
        {
            return ""
        }

        return tripinfo.get(ind).routetime
    }

    function getRouteRepeatInd(ind)
    {
        if (ind < 0 || ind > tripview.count)
        {
            return ""
        }

        return tripinfo.get(ind).routerepeat
    }

    function getRouteFrom()
    {
        if (activerouteind < 0 || activerouteind > tripinfo.count)
        {
            return ""
        }
        var frompoint = new DCDATA.DCRoutePoint();
        frompoint.type = "FROMPOINT"
        frompoint.pointset =  true
        frompoint.latitude =  tripinfo.get(activerouteind).routefromlat
        frompoint.longitude =  tripinfo.get(activerouteind).routefromlon
        frompoint.country =  tripinfo.get(activerouteind).routefromcountry
        frompoint.countryCode =  ""
        frompoint.state =  ""
        frompoint.city =  tripinfo.get(activerouteind).routefromcity
        frompoint.district =  ""
        frompoint.street =  tripinfo.get(activerouteind).routefromstreet
        frompoint.postcode =  tripinfo.get(activerouteind).routefrompostcode
        frompoint.distance =  0
        frompoint.traveltime =  0
        frompoint.routepolyline =  ""

        return frompoint;
    }

    function getRouteTo()
    {
        if (activerouteind < 0 || activerouteind > tripinfo.count)
        {
            return ""
        }
        var topoint = new DCDATA.DCRoutePoint();
        topoint.type = "TOPOINT"
        topoint.pointset =  true
        topoint.latitude =  tripinfo.get(activerouteind).routetolat
        topoint.longitude =  tripinfo.get(activerouteind).routetolon
        topoint.country =  tripinfo.get(activerouteind).routetocountry
        topoint.countryCode =  ""
        topoint.state =  ""
        topoint.city =  tripinfo.get(activerouteind).routetocity
        topoint.district =  ""
        topoint.street =  tripinfo.get(activerouteind).routetostreet
        topoint.postcode =  tripinfo.get(activerouteind).routetopostcode
        topoint.distance =  0
        topoint.traveltime =  0
        topoint.routepolyline =  ""

        return topoint;
    }

    function getCarpoolKarpoid()
    {
        if (activerouteind < 0 || activerouteind > tripinfo.count)
        {
            return ""
        }

        return tripinfo.get(activerouteind).carpoolkarpoid
    }

    function getPicklatlon(cpkarpoid)
    {
        var temp=[]

        var ind = -1
        for (var i = 0; i < tripinfo.count; i++)
        {
            if (tripinfo.get(i).carpoolkarpoid == cpkarpoid)
            {
                ind = i
            }
        }
        if (ind > -1)
        {
            temp[0] = tripinfo.get(ind).picklat
            temp[1] = tripinfo.get(ind).picklon
        }

        return temp
    }

    function loadTrips()
    {
        messagebox.showInfo("Loading the trips ...")

        tripinfo.clear()
        activerouteind = -1

        var mytripslist = new DCDATA.DCMyTripList();
        mytripslist.karpoid = karpoid;
        DCDATA.send(mytripslist, datacloudurl, "getmytrips", getcarpoolsofmembercb)

    }

    function getcarpoolsofmembercb(response)
    {
        console.log("MyTrips::gercarpoolsofmembercb: " + response.statusString)


        console.log("\r\n-----------\r\n" + JSON.stringify(response))

        if (response.mytriplist.length == 0)
        {
            messagebox.showInfo("You are not a member in any carpool.")
            tripview.currentIndex = -1
        }
        else
        {
            for (var i = 0; i < response.mytriplist.length; i++)
            {
                tripinfo.append(response.mytriplist[i])
            }
            tripview.currentIndex = 0
            messagebox.visible = false
        }
    }

    MessageBox
    {
        id: messagebox
        property string onOkTodo: "" // unjoinCarpool

        onOk:
        {
            if (onOkTodo == "unjoinCarpool")
            {
                unjoinCarpool()
            }

            onOkTodo = ""
        }

        onCancel:
        {
            onOkTodo = ""
        }

        function showInfo(msg)
        {
            messagebox.text = msg
            messagebox.show("")
        }
    }

    Rectangle
    {
        id: titlerect
        width: 110
        height: 29
        color: "#5d8eac"
        anchors.right: parent.right
        anchors.rightMargin: 0
        anchors.left: parent.left
        anchors.leftMargin: 0
        anchors.top: parent.top
        anchors.topMargin: 0

        Text {
            id: titleid
            width: 110
            height: 29
            text: "My trips"
            font.family: "Arial"
            anchors.leftMargin: 10
            anchors.fill: parent
            anchors.verticalCenter: titlerect.verticalCenter
            font.pixelSize: 16
        }

        MouseArea {
            id: titlerectmousearea
            anchors.fill: parent

            drag.target: mytripsrect
            drag.axis: Drag.XandYAxis
            drag.minimumX: 0
            drag.maximumX: 1000
            drag.minimumY: 0
            drag.maximumY: 1000
        }
    }




    Rectangle
    {
        id: listviewrect
        height: 40
        color: "#00000000"
        anchors.top:  titlerect.bottom
        anchors.topMargin: 5
        anchors.left: parent.left
        anchors.leftMargin: 10
        anchors.right: parent.right
        anchors.rightMargin: 10

        Component {
            id: tripDelegate
            Item {
                width: delegatesubrect.width+2;
                height: 40
                clip: true

                Rectangle
                {
                    id: delegatesubrect
                    width: childrenRect.width + 10;
                    height: 38
                    radius: 3
                    border.color: "#172862"
                    color: (tripview.currentIndex == index?"white":"lightblue")


                    Text { id: activelabel; text: (active=="1"?"[A]":""); color: "#237e23"; font.pixelSize: 12
                        anchors.top: parent.top; anchors.topMargin: 3; anchors.left: parent.left; anchors.leftMargin: 3; anchors.bottom: parent.bottom; anchors.bottomMargin: 0}

                    Text { id: tripname; text: routename; font.pixelSize: 12
                        anchors.top: parent.top; anchors.topMargin: 3;
                        anchors.left: activelabel.right; anchors.leftMargin: 3}

                    Text { text: routedescription; font.pixelSize: 10
                        anchors.left: activelabel.right; anchors.leftMargin: 3;
                        anchors.top: tripname.bottom; anchors.topMargin: 3}

                }


                MouseArea
                {
                    anchors.fill: parent

                    onPressed:
                    {
                        tripview.currentIndex = index
                    }


                    onDoubleClicked:
                    {
                        console.log("ROUTES NAME: " + tripinfo.get(index).routename + ", description = " + tripinfo.get(index).routedescription)
                        showSelectedRoute()
                    }
                }
            }
        }

        ListView {
            id: tripview
            clip: true
            orientation: ListView.Horizontal
            snapMode: ListView.SnapOneItem
            anchors.fill:  parent

            boundsBehavior: Flickable.StopAtBounds

            model: tripinfo
            delegate: tripDelegate

            focus: true


        }
    }
 // ---------

    function showSelectedRoute()
    {
        mytripsrect.showroute()

        var cpkarpoid = getCarpoolKarpoid()
        var latlon = getPicklatlon(cpkarpoid)
        if (latlon.length == 2)
        {
            console.log("++++++++++++ LAT,LON= " + latlon[0] + ", " + latlon[1])
            if (latlon[0] != "0" && latlon[1] != "0")
            {
                mytripsrect.drawImageOnMap("picklocation", latlon[0], latlon[1], "./qml/karpo/pickloc.png", -10,-34)
            }
        }
    }


    PushButton {
        id: followbutton
        width:  60
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        anchors.left: parent.left
        anchors.leftMargin: 10
        label: "Follow"
        onButtonpressed:
        {
            if (activerouteind < 0)
            {
                messagebox.showInfo("No trip selected.")
            }
            else
            {
                showSelectedRoute();

                mytripsrect.following = true
                mytripsrect.startFollowing(tripinfo.get(tripview.currentIndex).carpoolkarpoid)

                mytripsrect.visible = false
            }
        }
    }


    PushButton {
        id: unfollowbutton
        width:  60
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        anchors.left: followbutton.right
        anchors.leftMargin: 10
        label: "Unfollow"

        onButtonpressed:
        {
            mytripsrect.clearMap()
            mytripsrect.following = false
            mytripsrect.stopFollowing()

            mytripsrect.visible = false
        }
    }

    Timer {
        id: loadtripsagain
        interval: 2000
        running: false
        repeat: false
        onTriggered:
        {

            loadTrips()
        }

     }

    function deletecarpoolmembercb(result)
    {
        try
        {
            if (!result.isError)
            {
                loadtripsagain.start()

            }
            else
            {
                messagebox.text = "No trip was deleted"
                messagebox.show("")
            }
        }
        catch (ex)
        {
            messagebox.text = ex
            messagebox.show("")
        }
    }


    function unjoinCarpool()
    {
        messagebox.text = "Unjoining from the trip..."
        messagebox.show("")

        var cpkarpoid = getCarpoolKarpoid()
        var ind = -1
        for (var i = 0; i < tripinfo.count; i++)
        {
            if (tripinfo.get(i).carpoolkarpoid == cpkarpoid)
            {
                ind = i
            }
        }

        if (ind > -1)
        {
            console.log("DELETE MEMBER " + tripinfo.get(ind).memberindexkarpoid)

            var karpoids = []
            karpoids[0] = tripinfo.get(ind).memberindexkarpoid;

            var dckarpoidlist = new DCDATA.DCKarpoIdList();
            dckarpoidlist.username = username
            dckarpoidlist.karpoid = karpoid
            dckarpoidlist.password = password
            dckarpoidlist.karpoids = karpoids

            DCDATA.send(dckarpoidlist,datacloudurl, "deletecarpoolmembers", deletecarpoolmembercb)
        }
        else
        {
            messagebox.text = "Can't find the carpool."
            messagebox.show("")
        }


    }

    PushButton {
        id: deletebutton
        width:  60
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        anchors.left: unfollowbutton.right
        anchors.leftMargin: 10
        label: "Unjoin"

        onButtonpressed:
        {

            if (karpoid == tripinfo.get(tripview.currentIndex).ownerkarpoid)
            {
                messagebox.text = "This is your own trip.<br>Delete it in the Carpool dialog."
                messagebox.show("")
            }
            else
            {
                messagebox.text = "Do you want to unjoin from the route<br>" + tripinfo.get(tripview.currentIndex).routename + "?"
                messagebox.onOkTodo = "unjoinCarpool"
                messagebox.show("confirmation")
            }
        }
    }

    PushButton {
        id: closebutton
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        anchors.right: parent.right
        anchors.rightMargin: 10
        label: "Close"

        onButtonpressed:
        {
            if (!following)
            {
                mytripsrect.clearMap()
            }

            mytripsrect.visible = false
        }
    }
}
